<template>
    <div class="task-info-wrapper">
        <div class="inner-info">
            <div class="header">
                <h3>四、任务信息</h3>
            </div>
            <div class="form-main-content">
                <div class="time-select-a">
                    <div class="time-left" >
                        <!-- <a-button style="margin-right:10px;" type="primary"><router-link :to="'/orders/statistics/'+$route.params.id">订单统计</router-link></a-button><a-button  type="primary" @click="exports()">全部导出</a-button> -->
                    </div>
                    <div class="time-right">
                        <time-range style="" :time_range="taskMonth" :direction="true" @change="handleMonthChange"></time-range>
                        <a-select placeholder="全部" @change="taskStatusChange">
                            <a-select-option key="6">
                                已完成
                            </a-select-option>
                            <a-select-option key="0">
                                未完成
                            </a-select-option>
                        </a-select>
                    </div>
                </div>
                <a-table :columns="columns" rowKey="id" :dataSource="data" :pagination="pagination" bordered>
                    <span slot="report" slot-scope="record">
                        <a @click="showReport(record.id)">{{record.report_num}}</a>
                    </span>
                    <span slot="sn" slot-scope="record">
                        <router-link :to="'/task/update/'+record.id">{{record.sn}}</router-link>
                    </span>
                    <span slot="amount" slot-scope="record">
                            <a @click="showTaskAmount(record)">{{record.amount}}</a>
                        </span>
                        <span slot="action" slot-scope="record">
                                <div class="task-operate-container" v-if="user_id == dispatch_id">
                                    <a v-if="record.status_id==0 && [0,3,4,6].includes(record.cancel_status)" @click="handleTask(record,1)">取消此周期</a>
                                    <a v-if="record.status_id==0 && record.cancel_status==1" @click="handleTask(record,0)">恢复此周期</a>
                                    <a v-if="[1,2,3,4,8].includes(record.status_id)"
                                       @click="handleTask(record,6)">周期完成确认</a>
                                    <a v-if="record.status_id ==5"
                                       @click="handleTask(record,6)">重新修正</a>
                                    <a v-if="record.status_id ==3" @click="handleTask(record,8)">采集暂停</a>
                                    <a v-if="record.status_id ==8" @click="handleTask(record,3)">采集继续</a>
                                    <i v-if="record.status_id ==5 && record.cancel_status !==3">剩余{{record.rest_day}}自动确认</i>
                                    <i v-if="record.status_id ==6">此周期已完成</i>
                                    <i v-if="record.status_id ==7">此周期已取消</i>
                                </div>
                        </span>
                </a-table>
                <a-modal v-model="showRecoverPeriod" title="恢复周期" @ok="recoverPeriod"
                         :cancelButtonProps="{ props: {type: 'primary'}}"
                         cancelText="撤回"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <div class="confirm-delete-wrapper">
                        <p>是否恢复此周期？</p>
                    </div>
                </a-modal>
                <!-- 取消任务 -->
                <a-modal v-model="showcanceltask" title="取消周期" @ok="cancelTaskSubmit" @cancel="periodCancel"
                         :cancelButtonProps="{ props: {type: 'primary'}}"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <div class="confirm-wrapper">
                        <a-form :form="form_canceltask">
                            <a-form-item>
                                <a-textarea :rows="6" placeholder="周期取消原因"
                                            v-decorator="['reason',{rules: [{ required: true, message: '请输入周期取消原因' }]}]"/>
                            </a-form-item>
                        </a-form>
                    </div>
                </a-modal>
                <!-- 继续采集 -->
                <a-modal v-model="showContinueCollection" title="采集继续" @ok="operateContinueCollection"
                         :cancelButtonProps="{ props: {type: 'primary'}}"
                         cancelText="撤回"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <div class="confirm-delete-wrapper">
                        <p>是否继续采集？</p>
                    </div>
                </a-modal>
                <!-- 暂停采集 -->
                <a-modal v-model="showPauseCollection" title="采集暂停" @ok="operatePauseCollection"
                         :cancelButtonProps="{ props: {type: 'primary'}}"
                         cancelText="撤回"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <div class="confirm-delete-wrapper">
                        <p>是否暂停采集？</p>
                    </div>
                </a-modal>
                <!--周期完成确认-->
                <a-modal v-model="showtaskcomplete" title="周期完成确认" @ok="taskCompleteSubmit"
                         @cancel="periodCompleteCancel"
                         :cancelButtonProps="{ props: {type: 'primary'}}"
                         cancelText="撤回"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <a-form :form="form_taskcomplete">
                        <a-form-item>
                            计划扣除{{taskInfo.plan_amount}}积分，实际扣除
                            <a-input
                                    v-decorator="['amount',{initialValue:taskInfo.amount>0?taskInfo.amount:taskInfo.plan_amount},{rules: [{ required: true, message: '请输入积分值' }]}]"
                                    style="width:100px"/>
                            积分
                            <p>
                                <a-checkbox :checked="allperiod_price" @change="boxChange">其余周期均按照此额度进行扣除</a-checkbox>
                            </p>
                        </a-form-item>
                        <a-form-item>
                            <a-textarea :rows="6" placeholder="备注信息" v-decorator="['remark']"/>
                        </a-form-item>
                        <a-form-item label="上传凭证">
                            <a-upload
                                    listType="picture-card"
                                    :customRequest="uploadFile"
                                    :beforeUpload="beforeUpload"
                                    :fileList="fileList"
                                    :remove="handleCertificateChange"
                                    @preview="handlePreview"
                                    v-decorator="['images']"
                            >
                                <div v-if="fileList.length < 8" class="icon">
                                    <a-icon :type="loading ? 'loading' : 'plus'" :style="{fontSize: '30px'}"/>
                                    <div class="ant-upload-text"></div>
                                </div>
                            </a-upload>
                            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                                <img alt="example" style="width: 100%" :src="previewImage"/>
                            </a-modal>
                        </a-form-item>
                        <p>本周期所有工作已经完成交付</p>
                    </a-form>
                </a-modal>
                <!--点击扣除积分显示-->
                <a-modal v-model="showtaskamount" title="积分扣除信息"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <div class="integral-wrapper">
                        <div>
                            <p>计划扣除 {{taskInfo.plan_amount}} 积分，实际扣除 {{taskInfo.amount}} 积分</p>
                            <p>备注：{{taskInfo.remark ? taskInfo.remark : '无'}}</p>
                            <div>
                                <img style="width: 86px; height: 86px;" v-for="v in taskInfo.images" :src="v.url" :key="v"/>
                            </div>
                        </div>
                    </div>
                    <template slot="footer">
                        <a-button @click="showtaskamount = false" type="primary">确定</a-button>
                    </template>
                </a-modal>
                <!--显示报告模型-->
                <a-modal v-model="showreport" title="任务报告"
                         centered
                         :keyboard='false'
                         :maskClosable='false'>
                    <Report :task_id="task_id" :user_id="user_id" :dispatch_id="dispatch_id"></Report>
                    <template slot="footer">
                        <a-button @click="()=>showreport = false" type="primary">确定</a-button>
                    </template>
                </a-modal>
            </div>
        </div>
    </div>
</template>

<script>
    import moment from 'moment';
    import TimeRange from "../../components/timeRange";
    import {getBase64} from "@/utils/ImageBase64";
    import Report from "@/components/order/report";
    export default {
        name:'task',
        props:['order_id','dispatch_id'],
        components: {TimeRange,Report},
        data() {
            return {
                user_id: this.$store.getters.user_id,
                pagination: {
                    current: 1,
                    total: 0,
                    pageSize: 5,
                    showTotal: (total) => {
                        return '共' + total + '条'
                    },
                    onChange: (page, size) => {
                        this.handleChange(page, size)
                    },
                },
                data: [],
                columns: [
                    {title: "周期数", dataIndex: "num", align: "center"},
                    {title: "周期时间", dataIndex: "start_end", align: "center"},
                    {title: "任务编号", scopedSlots: {customRender: "sn"}, align: "center"},
                    {title: "任务状态", dataIndex: "status", align: "center"},
                    // {title: "报告数", scopedSlots: {customRender: "report"}, align: "center"},
                    {title: "计划扣除积分", dataIndex: "plan_amount", align: "center"},
                    {title: "实际扣除积分", scopedSlots: {customRender: "amount"}, align: "center"},
                    {title: "操作", scopedSlots: {customRender: "action"}, align: "center"},
                ],
                form_canceltask: this.$form.createForm(this),
                form_taskcomplete: this.$form.createForm(this),
                search: {},
                taskInfo: {},
                fileList: [],
                showtaskamount: false,
                taskMonth: moment().format('Y年MM月') + '-' + moment().format('Y年MM月'),
                showContinueCollection: false,
                showPauseCollection: false,
                cancelTaskStatus: 1,
                cancelTaskId: 0,
                showtaskcomplete: false,
                showcanceltask: false,
                allperiod_price: false,
                previewImage: false,
                previewVisible: false,
                loading: false,
                showRecoverPeriod: false,
                showreport:false,
                task_id:0
            }
        },

        mounted() {
            this.getList();
        },
        methods: {
            async getList(param = {}) {
                let req = {order_id: this.order_id, page_size: this.pagination.pageSize, page: this.pagination.current};

                let data = await this.http(
                    "get",
                    "task/index",
                    Object.assign(req, param)
                );
                this.data = data.data;
                this.pagination.total = data.total_count;
            },
            handleChange(page, size) {
                //列表展示条数改变
                this.pagination.current = page
                this.pagination.pageSize = size;
                this.getList(this.search);
            },
            taskStatusChange(value) {//任务状态改变
                if(value ==0){
                    value = '[0,1,2,3,4,5,8]'
                }
                this.getList({status: value})
            },
            handleMonthChange(changedFields) {//任务月份改变
                this.taskMonth = changedFields.time_range.value;
                let value = this.taskMonth.split('-');
                let month = {created_at: [moment(value[0], 'YYYY年MM月').format('YYYY-MM'), moment(value[1], 'YYYY年MM月').format('YYYY-MM')]}
                this.getList(month)
            },
            handleTask(data, status) {//显示操作任务
                this.cancelTaskId = data.id;
                this.cancelTaskStatus = status;
                let that = this;
                switch (status) {
                    case 0:
                        this.showRecoverPeriod = true;
                        break;
                    case 1:
                        this.showcanceltask = true;
                        break;
                    case 3:
                        this.showContinueCollection = true;
                        break;
                    case 6:
                        this.showtaskcomplete = true;
                        this.taskInfo = data;
                        this.allperiod_price = data.price_check>0?true:false
                        this.http('get', 'push/get-task-confirm', {id:data.id}).then(res => {
                            if(res.id !== undefined){
                                if(res.images !==''){
                                    this.fileList = res.images
                                }
                                
                                this.form_taskcomplete.setFieldsValue({remark:res.remark})
                            }
                        })
                        break;
                    case 8:
                        this.showPauseCollection = true;
                        break;
                }
            },
            periodCancel() {
                this.form_canceltask.resetFields();
            },
            recoverPeriod() {
                this.taskPut({cancel_status: this.cancelTaskStatus})
            },
            operateContinueCollection() {
                this.taskPut({status: this.cancelTaskStatus})
            },
            operatePauseCollection() {
                this.taskPut({status: this.cancelTaskStatus})
            },
            showTaskAmount(data) {
                this.showtaskamount = true
                this.taskInfo = data
            },
            cancelTaskSubmit() {//取消任务原因填写并提交
                this.form_canceltask.validateFields((err, values) => {
                    if (!err) {
                        values.cancel_status = this.cancelTaskStatus
                        this.taskPut(values)

                    }
                })
            },
            taskCompleteSubmit() {
                this.form_taskcomplete.validateFields((err, values) => {
                    if (!err) {
                        values.price_check = this.allperiod_price ? 1 : 0
                        values.status = this.cancelTaskStatus
                        if (values.images) {
                            let images = [];
                            this.fileList.map(m => {
                                images.push(m.name)
                            });
                            values.images = images
                        }
                        this.taskPut(values)
                        this.showtaskcomplete = false
                    }
                })
            },
            periodCompleteCancel() {
                this.form_taskcomplete.resetFields();
                this.fileList = [];
            },
            taskPut(data) {
                this.http('put', 'task/update?id=' + this.cancelTaskId, data).then(res => {
                    if (res.id) {
                        this.showcanceltask = false;
                        this.getList()
                    } else {
                        this.$message.error(res.msg, 1);
                    }

                    this.showRecoverPeriod = false;
                    this.showContinueCollection = false;
                    this.showPauseCollection = false;
                })
            },
            beforeUpload(file) {
                const typeB = file.type == "image/jpeg" || file.type == "image/png";
                if (!typeB) {
                    this.$message.error("请选择jpg,png格式的图片", 1);
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error("图片大小必须小于2MB!", 1);
                }
                return typeB && isLt2M;
            },
            uploadFile(file) {//上传周期完成确认凭证
                getBase64(file.file, base64 => {
                    this.http("post", "upload/upload", {image: base64}).then(res => {
                        this.fileList.push({uid: this.fileList.length + 1, name: res.url, url: res.imgurl})
                        this.loading = false;
                    });
                });
            },
            boxChange(e) {
                this.allperiod_price = e.target.checked
            },
            handleCertificateChange() {
                this.fileList = this.fileList.filter(item => {
                    return item.status !== 'removed'
                });
            },
            handlePreview(file) {
                this.previewImage = file.url || file.thumbUrl
                this.previewVisible = true
            },
            handleCancel() {
                this.previewVisible = false
            },
            /**显示报告 */
            showReport(task_id){
                this.showreport = true
                this.task_id = task_id
            },
            /**导出全部报告 */
            exports(){
                let  params = {status:1,export:1,not_selects:'',order_id:this.order_id}
                open(process.env.VUE_APP_BASE_URL+'report/export?'+qs.stringify(params),'_blank')
            }
        }
    };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "./../../assets/scss/mixin";

    .task-info-wrapper {
        border-bottom: 1px solid #1E2026;
        padding-bottom: 20px;
        margin-bottom: 20px;

        .inner-info {
            padding-left: 24px;
            padding-right: 24px;

            .time-select-a {
                @include fj(space-between);
                margin: 20px 0px;
                
                .ant-select {
                    width: 200px;
                }
                .time-right{
                    display: flex;
                    /deep/.ant-form-item-children{
                        padding-right: 15px;
                    }
                }
            }
        }
    }

    .confirm-delete-wrapper {
        width: 100%;
        padding: 20px;
        text-align: center;

        p {
            font-size: 16px;
        }
    }

    .task-operate-container {
        a, i {
            display: block;
        }
    }

    .integral-wrapper {
        width: 100%;
        p {
            font-size: 16px;
        }
        @include centering;
        & > div {
            p + p {
                margin-top: 10px;
            }
            & > div {
                margin-top: 20px;
                img + img {
                    margin-left: 10px;
                }
            }
        }
    }
</style>
